const data = [
  {
    id: 15261,
    user_id: 190,
    name: '阎军',
    age: 24,
    gender: 1,
    hope_salary: 12000,
    salary: 10200,
    group: 8,
    province: '北京',
    city: '北京市',
    area: '顺义区',
    createdAt: '2023-03-03T03:15:31.000Z',
    updatedAt: '2023-03-03T03:15:31.000Z',
  },
  {
    id: 15260,
    user_id: 190,
    name: '萧明',
    age: 26,
    gender: 1,
    hope_salary: 10500,
    salary: 11400,
    group: 7,
    province: '福建省',
    city: '厦门市',
    area: '翔安区',
    createdAt: '2023-03-03T03:15:31.000Z',
    updatedAt: '2023-03-03T03:15:31.000Z',
  },
  {
    id: 15259,
    user_id: 190,
    name: '韩秀英',
    age: 19,
    gender: 0,
    hope_salary: 14800,
    salary: 18500,
    group: 6,
    province: '湖南省',
    city: '湘潭市',
    area: '岳塘区',
    createdAt: '2023-03-03T03:15:31.000Z',
    updatedAt: '2023-03-03T03:15:31.000Z',
  },
];

//无数据测试用
const adata = [];

// 1. 初始化渲染

//根据本阶段学习的js基础知识，请封装完成一个渲染函数renderList，要求利用分支，循环，对象属性等知识

// 无数据时请使用下面这一选项
// document.querySelector(".list").innerHTML = `<img src='../lib/nocontent.png'>`

// 循环渲染时需要的数据结构，请将对应的数据填入

// let html = ``
// `<tr>
//       <td>${name}</td>
//       <td>${age}</td>
//       <td>${性别（女生为0，男生为1）}</td>
//       <td>第${group}组</td>
//       <td>${hope_salary}</td>
//       <td>${salary}</td>
//       <td>${province} ${city} ${area}</td>
//       <td>
//         <a href="javascript:;" class="text-success mr-3"><i data-id=${id
// } class="bi bi-pen"></i></a>
//         <a href="javascript:;" class="text-danger"><i data-id=${id
// } class="bi bi-trash"></i></a>
//       </td>
//     </tr >
// `

// 当完成模版以后使用下面两行输出即可

//函数封装部分结束
function renderList(data) {
  let html = ``;
  if (data.length === 0) {
    return document.querySelector(
      '.list'
    ).innerHTML = `<img src='../lib/nocontent.png'>`;
   ;
  }
  for (let i = 0; i < data.length; i++) {
    html += `<tr>
      <td>${data[i].name}</td>
      <td>${data[i].age}</td>
      <td>${data[i].gender ? '男' : '女'}</td>
      <td>第${data[i].group}组</td>
      <td>${data[i].hope_salary}</td>
      <td>${data[i].salary}</td>
      <td>${data[i].province} ${data[i].city} ${data[i].area}</td>
      <td>
        <a href="javascript:;" class="text-success mr-3"><i data-id=${
          data[i].id
        } class="bi bi-pen"></i></a>
        <a href="javascript:;" class="text-danger"><i data-id=${
          data[i].id
        } class="bi bi-trash"></i></a>
      </td>
    </tr >
`;
  }
  document.querySelector('.list').innerHTML = html;
  document.querySelector('.total').innerHTML = data.length;
}
renderList(data);

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal');
const modal = new bootstrap.Modal(modalBox);
const ps = document.querySelector('[name=province]');
const cs = document.querySelector('[name=city]');
const as = document.querySelector('[name=area]');
const initCity = async () => {
  // 显示省市区
  const { data: province } = await axios.get('/api/province');
  const phtml = province
    .map((item) => `< option value = "${item}" > ${item}</ > `)
    .join('');
  ps.innerHTML = `< option value = "" > --省份--</ > ${phtml} `;
  // 省市区联动
  ps.addEventListener('change', async () => {
    cs.value = '';
    as.value = '';
    const { data: city } = await axios.get('/api/city', {
      params: { pname: ps.value },
    });
    const chtml = city
      .map((item) => `< option value = "${item}" > ${item}</ > `)
      .join('');
    cs.innerHTML = `< option value = "" > --市--</ > ${chtml} `;
  });
  cs.addEventListener('change', async () => {
    as.value = '';
    const { data: area } = await axios.get('/api/area', {
      params: { pname: ps.value, cname: cs.value },
    });
    const ahtml = area
      .map((item) => `< option value = "${item}" > ${item}</ > `)
      .join('');
    as.innerHTML = `< option value = "" > --区--</ > ${ahtml} `;
  });
};
initCity();

// 2. 添加学生
document.querySelector('#openModal').addEventListener('click', () => {
  modalBox.querySelector('form').reset();
  modalBox.querySelector('.modal-title').innerHTML = '添加学员';
  modalBox.dataset.id = 'add';
  modal.show();
});
const form = modalBox.querySelector('form');
document.querySelector('#submit').addEventListener('click', async () => {
  const data = serialize(form, { hash: true });
  //数据要进行类型转换
  data.age = +data.age;
  data.hope_salary = +data.hope_salary;
  data.salary = +data.salary;
  data.gender = +data.gender;
  data.group = +data.group;

  //根据id的关键词进行判断
  if (modalBox.dataset.id !== 'add') {
    try {
      await axios.put(`/ students / ${modalBox.dataset.id} `, data);
      modal.hide();
      renderList();
    } catch (error) {
      alert('修改失败');
    }
  } else {
    try {
      await axios.post('/students', data);
      modal.hide();
      renderList();
    } catch (error) {
      alert('添加失败');
    }
  }
});

// 3. 删除学生
document.querySelector('.list').addEventListener('click', async (e) => {
  const btn = e.target;
  if (btn.classList.contains('bi-trash')) {
    // 删除
    try {
      await axios.delete(`/ students / ${btn.dataset.id} `);
      renderList();
    } catch (error) {
      alert('删除失败');
    }
  }
  if (btn.classList.contains('bi-pen')) {
    // 编辑
    const { data: student } = await axios.get(
      `/ students / ${btn.dataset.id} `
    );
    const fields = modalBox.querySelectorAll('form [name]');
    Array.from(fields).forEach(async (item) => {
      if (item.name === 'gender') {
        if (+item.value === student[item.name]) item.checked = true;
      } else {
        item.value = student[item.name];
      }
    });
    const { data: city } = await axios.get('/api/city', {
      params: { pname: ps.value },
    });
    const chtml = city
      .map((item) => `< option value = "${item}" > ${item}</ > `)
      .join('');
    cs.innerHTML = `< option value = "" > --市--</ > ${chtml} `;
    cs.value = student.city;
    const { data: area } = await axios.get('/api/area', {
      params: { pname: ps.value, cname: cs.value },
    });
    const ahtml = area
      .map((item) => `< option value = "${item}" > ${item}</ > `)
      .join('');
    as.innerHTML = `< option value = "" > --区--</ > ${ahtml} `;
    as.value = student.area;

    modalBox.querySelector('.modal-title').innerHTML = '修改学员';
    // 记录ID修改使用
    modalBox.dataset.id = student.id;
    modal.show();
  }
});
